<template>
  <PageContainer>
    <div class="upload-page">
      <div class="upload-header">
        <h1 class="page-title">图片上传</h1>
        <p class="page-description">上传图片并使用AI自动识别标签，生成精彩文案</p>
      </div>
      
      <!-- 上传区域 -->
      <div class="upload-section" v-show="currentStep === 'upload'">
        <UploadArea 
          @select="handleFileSelect"
          :disabled="isUploading"
        />
        
        <UploadProgress 
          v-if="progressItems.length > 0"
          :progress-items="progressItems"
          @view="handleViewProgress"
          @retry="handleRetryUpload"
          @remove="handleRemoveProgress"
          @upload-all="handleUploadAll"
          @clear-all="handleClearAll"
        />
      </div>
      
      <!-- 上传结果 -->
      <div class="result-section" v-show="currentStep === 'result'">
        <UploadResult 
          :uploaded-images="uploadedImages"
          @view-image="handleViewImage"
          @generate-text="handleGenerateText"
          @continue-upload="handleContinueUpload"
        />
      </div>
      
      <!-- 图片预览对话框 -->
      <el-dialog
        v-model="previewVisible"
        title="图片预览"
        width="80%"
        :before-close="handleClosePreview"
      >
        <div class="preview-content" v-if="previewImage">
          <div class="preview-image-container">
            <img :src="previewImage.fileUrl" :alt="previewImage.name" class="preview-image" />
          </div>
          <div class="preview-info">
            <h3>{{ previewImage.originalName }}</h3>
            <div class="preview-meta">
              <p><strong>文件大小:</strong> {{ formatFileSize(previewImage.fileSize) }}</p>
              <p><strong>图片尺寸:</strong> {{ previewImage.width }}×{{ previewImage.height }}</p>
              <p><strong>上传时间:</strong> {{ formatDate(previewImage.createdAt) }}</p>
              <p><strong>AI识别状态:</strong> 
                <el-tag :type="getStatusTagType(previewImage.aiRecognitionStatus)">
                  {{ getAiStatusText(previewImage.aiRecognitionStatus) }}
                </el-tag>
              </p>
            </div>
            <div class="preview-tags" v-if="previewImage.tags && previewImage.tags.length > 0">
              <h4>AI识别标签:</h4>
              <div class="tags-container">
                <el-tag 
                  v-for="tag in previewImage.tags" 
                  :key="tag"
                  class="tag-item"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </div>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageContainer from '@/components/layout/PageContainer.vue'
import UploadArea from '@/components/upload/UploadArea.vue'
import UploadProgress from '@/components/upload/UploadProgress.vue'
import UploadResult from '@/components/upload/UploadResult.vue'
import { uploadImage, getImageById } from '@/api/image'
import { triggerAiRecognition } from '@/api/ai'
import type { UploadProgress as UploadProgressType, ImageModel } from '@/types'
import { formatFileSize, formatDate } from '@/utils'

// 响应式数据
const currentStep = ref<'upload' | 'result'>('upload')
const isUploading = ref(false)
const progressItems = ref<UploadProgressType[]>([])
const uploadedImages = ref<ImageModel[]>([])
const previewVisible = ref(false)
const previewImage = ref<ImageModel | null>(null)
const router = useRouter()

// 计算属性
const hasUploadedImages = computed(() => uploadedImages.value.length > 0)

// 方法
const handleFileSelect = async (files: File[]) => {
  // 创建进度项
  const newProgressItems = files.map(file => ({
    file,
    progress: 0,
    status: 'pending' as const,
    error: null
  }))
  
  progressItems.value.push(...newProgressItems)
  
  // 自动开始上传
  await handleUploadAll()
}

const handleUploadAll = async () => {
  const pendingItems = progressItems.value.filter(item => 
    item.status === 'pending' || item.status === 'error'
  )
  
  if (pendingItems.length === 0) {
    ElMessage.info('没有需要上传的文件')
    return
  }
  
  isUploading.value = true
  
  // 并发上传文件
  const uploadPromises = pendingItems.map(async (item, index) => {
    try {
      // 更新状态为上传中
      item.status = 'uploading'
      item.progress = 0
      
      // 创建FormData
      const formData = new FormData()
      formData.append('file', item.file)
      
      // 上传文件
      const response = await uploadImage(formData, (progressEvent) => {
        if (progressEvent.total) {
          item.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
        }
      })
      
      // 上传成功
      item.status = 'success'
      item.progress = 100
      
      // 添加到已上传列表
      uploadedImages.value.push(response.data)
      
      // 触发AI识别
      try {
        await triggerAiRecognition(response.data.id)
      } catch (aiError) {
        console.warn('AI识别触发失败:', aiError)
      }
      
    } catch (error: any) {
      // 上传失败
      item.status = 'error'
      item.error = error.response?.data?.message || '上传失败'
      console.error('文件上传失败:', error)
    }
  })
  
  await Promise.all(uploadPromises)
  
  isUploading.value = false
  
  // 如果有成功上传的文件，切换到结果页面
  if (uploadedImages.value.length > 0) {
    ElMessage.success(`成功上传 ${uploadedImages.value.length} 个文件`)
    currentStep.value = 'result'
  }
}

const handleRetryUpload = async (item: UploadProgressType, index: number) => {
  try {
    item.status = 'uploading'
    item.progress = 0
    item.error = null
    
    const formData = new FormData()
    formData.append('file', item.file)
    
    const response = await uploadImage(formData, (progressEvent) => {
      if (progressEvent.total) {
        item.progress = Math.round((progressEvent.loaded * 100) / progressEvent.total)
      }
    })
    
    item.status = 'success'
    item.progress = 100
    
    uploadedImages.value.push(response.data)
    
    // 触发AI识别
    try {
      await triggerAiRecognition(response.data.id)
    } catch (aiError) {
      console.warn('AI识别触发失败:', aiError)
    }
    
    ElMessage.success('重新上传成功')
    
  } catch (error: any) {
    item.status = 'error'
    item.error = error.response?.data?.message || '上传失败'
    ElMessage.error('重新上传失败')
  }
}

const handleRemoveProgress = (item: UploadProgressType, index: number) => {
  progressItems.value.splice(index, 1)
}

const handleClearAll = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有上传记录吗？',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    progressItems.value = []
    ElMessage.success('已清空上传记录')
    
  } catch {
    // 用户取消
  }
}

const handleViewProgress = (item: UploadProgressType) => {
  // 可以实现查看进度详情的逻辑
  console.log('查看进度:', item)
}

const handleViewImage = (image: ImageModel) => {
  previewImage.value = image
  previewVisible.value = true
}

const handleGenerateText = (image: ImageModel) => {
  // 跳转到文案生成页面
  router.push({
    name: 'TextGeneration',
    query: { imageId: image.id }
  })
}

const handleContinueUpload = () => {
  currentStep.value = 'upload'
}

const handleClosePreview = () => {
  previewVisible.value = false
  previewImage.value = null
}

const getStatusTagType = (status: string) => {
  switch (status) {
    case 'SUCCESS': return 'success'
    case 'FAILED': return 'danger'
    default: return 'warning'
  }
}

const getAiStatusText = (status: string) => {
  switch (status) {
    case 'SUCCESS': return 'AI识别成功'
    case 'FAILED': return 'AI识别失败'
    default: return 'AI识别中'
  }
}
</script>

<style scoped>
.upload-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.upload-header {
  text-align: center;
  margin-bottom: 40px;
}

.page-title {
  font-size: 2.5rem;
  font-weight: 700;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.page-description {
  font-size: 1.1rem;
  color: rgba(255, 255, 255, 0.8);
  margin: 0;
}

.upload-section,
.result-section {
  display: flex;
  flex-direction: column;
  gap: 30px;
}

.preview-content {
  display: flex;
  gap: 30px;
}

.preview-image-container {
  flex: 1;
  text-align: center;
}

.preview-image {
  max-width: 100%;
  max-height: 500px;
  border-radius: 10px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.preview-info {
  flex: 1;
  min-width: 300px;
}

.preview-info h3 {
  color: #333;
  margin-bottom: 20px;
  font-size: 1.3rem;
}

.preview-meta {
  margin-bottom: 20px;
}

.preview-meta p {
  margin: 8px 0;
  color: #666;
}

.preview-tags h4 {
  color: #333;
  margin-bottom: 10px;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  cursor: default;
}

@media (max-width: 768px) {
  .upload-page {
    padding: 15px;
  }
  
  .page-title {
    font-size: 2rem;
  }
  
  .page-description {
    font-size: 1rem;
  }
  
  .preview-content {
    flex-direction: column;
  }
  
  .preview-info {
    min-width: auto;
  }
}
</style>